package com.ruitaowang.account.service;

import com.ruitaowang.account.dao.*;
import com.ruitaowang.core.domain.Resource;
import com.ruitaowang.core.domain.Role;
import com.ruitaowang.core.domain.RoleResourceLink;
import com.ruitaowang.core.domain.UserRoleLink;
import com.ruitaowang.core.service.BaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by neal on 11/7/16.
 */
@Service
public class RoleService implements BaseService<Role> {
    protected final Logger LOGGER = LoggerFactory.getLogger(getClass());
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleAdMapper roleAdMapper;

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private RoleResourceLinkMapper roleResourceLinkMapper;

    @Autowired
    private UserRoleLinkMapper userRoleLinkMapper;

    @Autowired
    private UserRoleLinkAdMapper userRoleLinkAdMapper;

    public Role insert(Role role) {
        Long time = System.currentTimeMillis();
        role.setCtime(time);
        role.setMtime(time);
        roleMapper.insert(role);
        return role;
    }

    public int delete(Long id) {
        return roleMapper.deleteByPK(id);
    }

    public Role update(Role role) {
        roleMapper.updateByPK(role);
        return role;
    }

    public Role selectByPK(Long id) {
        return roleMapper.selectByPK(id);
    }

    public List<Role> select(Role role) {
        role.setTotal(roleMapper.count(role));
        role.setResult(roleMapper.select(role));
        return role.getResult();
    }

    public List<Role> selectBatch(Long userId) {
        UserRoleLink userRoleLink = new UserRoleLink();
        userRoleLink.setUserId(userId);
        List<UserRoleLink> userRoleLinks = userRoleLinkMapper.select(userRoleLink);
        if(ObjectUtils.isEmpty(userRoleLinks)){
            return null;
        }
        List<Long> roleIds = new ArrayList<>();
        userRoleLinks.forEach(item -> {
            roleIds.add(item.getRoleId());
        });

        return roleAdMapper.selectBatch(roleIds);
    }

    public List<Role> selectByResourceURI(String uri) {

        Resource resource = new Resource();
        resource.setLink(uri);
        List<Resource> resources = resourceMapper.select(resource);
        if (resources == null || resources.size() == 0) {
            return null;
        }
        resource = resources.get(0);
        RoleResourceLink roleResourceLink = new RoleResourceLink();
        roleResourceLink.setResourceId(resource.getId());
        List<RoleResourceLink> roleResourceLinks = roleResourceLinkMapper.select(roleResourceLink);

        if (roleResourceLinks == null || roleResourceLinks.size() == 0) {
            return null;
        }

        List<Long> roleIds = new ArrayList<>();
        roleResourceLinks.forEach(item -> {
            roleIds.add(item.getRoleId());
        });

        return roleAdMapper.selectBatch(roleIds);
    }

    public void grantUserRole(Long userId, String roleIds){
        if (roleIds == null){
            return;
        }
        userRoleLinkAdMapper.deleteByUserId(userId);
        if ("-1".equals(roleIds)){
            return;//清空全部
        }
        Arrays
            .asList(roleIds.split(","))
            .stream()
            .map(item -> Long.valueOf(item))
            .forEach(roleId ->
            {
                UserRoleLink userRoleLink = new UserRoleLink();
                userRoleLink.setUserId(userId);
                userRoleLink.setRoleId(roleId);
                Long time = System.currentTimeMillis();
                userRoleLink.setCtime(time);
                userRoleLink.setMtime(time);
                userRoleLinkMapper.insert(userRoleLink);
            });
    }
    public void grantUserRoleForAppend(Long userId, String roleIds){
        if (roleIds == null){
            return;
        }
        if ("-1".equals(roleIds)){
            return;//清空全部
        }
        Arrays
            .asList(roleIds.split(","))
            .stream()
            .map(item -> Long.valueOf(item))
            .forEach(roleId ->
            {
                UserRoleLink userRoleLink = new UserRoleLink();
                userRoleLink.setUserId(userId);
                userRoleLink.setRoleId(roleId);
                Long time = System.currentTimeMillis();
                userRoleLink.setCtime(time);
                userRoleLink.setMtime(time);
                try{
                    userRoleLinkMapper.insert(userRoleLink);
                }catch (Exception e){
                    LOGGER.debug("userId: {}, roleId: {}", userId, roleId);
                }

            });
    }
//    public List<Role> selectByPid(){
////        return roleAdMapper.selectByPid();
////    }
}
